﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace CGSR.Core
{
    public class SimulationLocationsManager
    {
        //public Location[][] LocationsPerTick { get; set; }
        public double MaxX { get; set; }
        public double MaxY { get; set; }
        public int NumOfTicks { get; set; }
        public int NumOfUsers { get; set; }
        StreamReader readFile;

        public SimulationLocationsManager(string locationsFilePath)
        {
            
            readFile = new StreamReader(locationsFilePath);
            
            string line;

			///  first line
			if ((line = readFile.ReadLine()) != null)
			{
				ParseFirstRow(line);
			}
			//LocationsPerTick = new Location[NumOfTicks][];
        }

        private void ParseFirstRow(string line)
        {
            string[] row = line.Split(',');
            
            int numofticks;
            if (int.TryParse(row[1].Split('=')[1], out numofticks))
            {
                this.NumOfTicks = numofticks;
            }
            else throw new Exception("No NumOfTicks in the Location file");

            int numofusers;
            if (int.TryParse(row[0].Split('=')[1], out numofusers))
            {
                this.NumOfUsers = numofusers;
            }
            else throw new Exception("No NumOfUsers in the Location file");

            double maxX;
            if (double.TryParse(row[2].Split('=')[1], out maxX))
            {
                this.MaxX = maxX;
            }
            else throw new Exception("No MaxX in the Location file");

            double maxY;
            if (double.TryParse(row[3].Split('=')[1], out maxY))
            {
                this.MaxY = maxY;
            }
            else throw new Exception("No MaxX in the Location file");
        }

        public Location[] GetLocationsForNextTick()
        {
            string[] row;
            var line = readFile.ReadLine();
            
            row = line.Split(',');
//            if (row.Length == 0 || row[0].Length == 0 || row[0][0] == '#')
//                continue;
            int tick = int.Parse(row[0].Replace("T", ""));
            Location[] locations = new Location[NumOfUsers];

            for (int i = 0; i < row.Length / 2; i++)
            {
                locations[i] = new Location(int.Parse(row[i * 2 + 1]), int.Parse(row[i * 2 + 2]));
            }
            return locations;
            
        }
    }
}
